import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import { Validators } from '@angular/forms';
import { AdminService, AdminModel } from '../services/admin.service';
import {
  markAllAsTouched,
  formGroupToFormData,
  firstInvalid,
  confirmPassword,
} from 'app/modules/base/helper';
import { DetailBase } from 'app/modules/base/detail-base';
import { MatTabGroup } from '@angular/material';

@Component({
  selector: 'm-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss'],
})
export class AddComponent extends DetailBase implements OnInit {
  constructor(private injector: Injector, private adminService: AdminService) {
    super(injector);
  }
  @ViewChild(MatTabGroup) tabs: MatTabGroup;
  form = this.fb.group(
    {
      id: [0],
      level_struct: ['', Validators.required],
      username: ['', Validators.required],
      password: ['', Validators.required],
      confirm: ['', Validators.required],
      full_name: ['', Validators.required],
      phone: ['', [Validators.pattern(/^1\d{10}$/)]],
      email: ['', Validators.email],
      remark: [''],
      photo: [''],
      area_ids: [[], Validators.required],
      auth_ids: [[]],
    },
    { validators: [confirmPassword()] },
  );
  pwdForm = this.fb.group(
    {
      password: ['', Validators.required],
      confirm: ['', Validators.required],
    },
    { validators: [confirmPassword()] },
  );
  admin_info = this.route.snapshot.data.data as AdminModel;
  admin_list = this.route.snapshot.data.list as AdminModel[];
  ngOnInit() {
    if (this.admin_info) {
      const editModelRemoveControl = ['password', 'confirm', 'level_struct'];
      this.form.setValidators(null);
      editModelRemoveControl.forEach(control => this.form.removeControl(control));
      this.form.patchValue(this.admin_info);
    }
  }

  async submit() {
    markAllAsTouched(this.form);
    if (this.form.invalid) {
      if (firstInvalid(this.form).includes('area_ids')) {
        this.tabs.selectedIndex = 1;
        return;
      }
      this.tabs.selectedIndex = 0;
      return;
    }
    const data = formGroupToFormData(this.form);
    if (this.admin_info) {
      await this.adminService.update(data);
      this.back();
    } else {
      await this.adminService.create(data);
      this.back({ level: 1 });
    }
  }
  async delete() {
    const result = await this.sweet.confirm(`确定要删除${this.admin_info.username}吗？`);
    if (result.dismiss) {
      return;
    }
    await this.adminService.delete([this.admin_info.id]);
    this.back();
  }
}
